
#include <ESP8266WiFi.h>
#include "OneButton.h"
#include "led.h"

WiFiClient wifiClient;

class SmartWifi
{
private:
    bool connecting = false;

public:
    LED led;
    SmartWifi(const int led_pin = LED_BUILTIN, const boolean active_low = true)
    {
        this->led = LED(led_pin, active_low);
    }

    bool autoConnect()
    {
        WiFi.begin();
        int i = 0;
        this->led.on();
        while (true)
        {
            int state = WiFi.status();
            if (state == WL_CONNECTED)
            {
                Serial.println("WiFi connected");
                Serial.println("IP address: ");
                Serial.println(WiFi.localIP());
                this->led.off();
                return true;
            }
            else if (state == WL_DISCONNECTED)
            {
                Serial.print(".");
                this->led.toggle();
            }
            else
            {
                Serial.print("WiFi status:");
                Serial.println(state);
                this->led.on();
                return false;
            }
            delay(300);
            i++;
            if (i > 30)
            {
                Serial.println("WiFi连接失败");
                this->led.on();
                return false;
            }
        }
        this->led.off();
        return true;
    }

    void smartConfig()
    {
        WiFi.beginSmartConfig();
        Serial.print("等待配置");
        this->led.on();
        while (!WiFi.smartConfigDone())
        {
            this->led.toggle();
            Serial.print(".");
            delay(500);
        }
        this->led.off();
        Serial.println("配置成功");
    }

    void begin()
    {
        if (!autoConnect())
        {
            smartConfig();
        }
    }

    void loop()
    {
    }
};
